package hospital.msm.controller;

import com.mysql.jdbc.StringUtils;
import hospital.msm.service.MsmService;
import hospital.msm.utils.RandomUtil;
import hospital.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author
 * @description:
 */
@Api("阿里云接口")
@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * @Author yang
     * @Description //TODO 发送手机验证码
     * @Param
     * @return
     **/
    @ApiOperation("发送手机验证码")
    @GetMapping("/send/{phone}")
    public Result send(@PathVariable String phone){
        //先从Redis中获取验证码，如果能获取到，返回OK
        //key phone value code
        String code = redisTemplate.opsForValue().get(phone);
        //返回OK
        if(!StringUtils.isNullOrEmpty(code)){
            return Result.ok();
        }

        //如果从Redis中获取不到
        //生成验证码
        code = RandomUtil.getSixBitRandom();
        //生成验证码，整合到短信服务，进行发送
       boolean isSend=msmService.send(phone,code);
        //钱不够用，用固定值代替,需要事，注释掉此代码
        //code="123456";
        //boolean isSend=true;

        //将生成的验证码放在Redis里面，设置有效时间
        //成功发送
        if(isSend){
            //先删除之前的key
            redisTemplate.delete(phone);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        }else{
            return Result.fail("短信发送失败");
        }
        return null;
    }
}
